package com.powernode.config;

import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.filter.TokenTranslationFilter;
import com.powernode.model.Result;
import com.powernode.util.JSONUtils;
import com.powernode.util.ResponseUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 *
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private TokenTranslationFilter tokenTranslationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 关闭跨站请求伪造
        http.csrf().disable();
        // 关闭跨域请求
        http.cors().disable();
        // 关闭session管理
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 编写token及西俄过滤器 , 加ingtoken转换为用户信息存放到security容器 , 放在认证过滤器之前 , 无需再登录
        http.addFilterBefore(tokenTranslationFilter, UsernamePasswordAuthenticationFilter.class);
        // 没有携带token , 直接访问资源服务器 , 拦截报401 , 如果由token但没有访问权限, 报403
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint())  // 处理：没有携带token的请求直接访问资源服务器
                .accessDeniedHandler(accessDeniedHandler()); // 处理：携带token，但是权限不够
        // 配置放ii你路径
        http.authorizeHttpRequests()
                .antMatchers("/**") // 放行路径ResourceConstants.RESOURCE_ALLOW_URLS
                .permitAll()
                .anyRequest()
                .authenticated();
    }

    /**
     * 没有携带token的 请求 直接访问资源服务器
     * 401 未授权  ---> 没有权限,白日做梦
     *
     * @return
     */
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request , response , authException) -> {
            // 设置响应头
            response.setContentType(HttpConstants.APPLICATION_JSON);
            response.setCharacterEncoding(HttpConstants.UTF_8);
            // 返回响应结果 -- 拦截报401
            Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);// 401 未授权
            ResponseUtils.writer(response, JSONUtils.objToJson(result));
        };
    }

    /**
     * 携带token，但是权限不够
     * 403 权限不够   --->  有权限但不够
     *
     * @return
     */
    public AccessDeniedHandler accessDeniedHandler() {
        return (request , response , authException) -> {
            // 设置响应头
            response.setContentType(HttpConstants.APPLICATION_JSON);
            response.setCharacterEncoding(HttpConstants.UTF_8);
            // 返回响应结果 -- 拦截报401
            Result<Object> result = Result.fail(BusinessEnum.ACCESS_DENY_FAIL);// 403 权限不够
            ResponseUtils.writer(response, JSONUtils.objToJson(result));
        };
    }
}
